<!--
 * @Author: Lizhenyu
 * @Date: 2021-07-15 11:36:09
 * @FilePath: \usp-osm-frondend\src\views\productCenter\productMgmt\updateProduct.vue
-->
<template>
  <div class="source" v-loading="pageLoading" :element-loading-text="loadingText">
    <div class="newPageTitle">
      <span class="backIcon" @click="closeDialog"><i class="el-icon-back"></i></span>
      <h1 style="display:inline-block;margin-left:10px">{{pageTitle}}</h1>
    </div>
    <el-steps :active="nowStep" finish-status="success" class="stepStyle" align-center>
      <el-step :icon="nowStep === 0 ? 'el-icon-edit': ''" title="第一步"></el-step>
      <el-step :icon="nowStep === 1 ? 'el-icon-edit': ''" title="第二步"></el-step>
    </el-steps>
    <step-one
      v-if="showStepOne"
      v-show="nowStep === 0"
      ref="stepOne"
      :model="parentModel"
      :type="prodType"
      :isShow="isShow"
      :operationType="operationType"
      @startLoading="startLoading"
      @next="next"
      @cancel="closeDialog"
      @setModel="setModel"
      @submit="submit"
      @alertFlag="alertFlag"
    ></step-one>
    <step-two
      v-show="nowStep === 1"
      ref="stepTwo"
      :model="parentModel"
      @startLoading="startLoading"
      @next="next"
      @cancel="closeDialog"
      @back="prev"
      @submit="submit"
    ></step-two>
  </div>
</template>

<script>
import { getSpuById, getSkuById, productSave } from '@/api/product'
import { setRouterParams, getRouterParams } from '@/utils/auth'
import StepOne from './StepOne.vue'
import StepTwo from './StepTwo.vue'
import { common } from '@/mixins/common'
export default {
  name: 'ProductAdd',
  mixins: [common],
  components: { StepOne, StepTwo },
  data () {
    return {
      isAlert: false,
      Isupdate: false,
      showStepOne: true,
      loading: false,
      nowStep: 0,
      isEdit: false,
      productDatas: null,
      loadingText: '加载中...',
      submitDatas: {},
      parentModel: {
        catalogId: '',
        cancelable: '1',
        returnable: '1',
        categoryDatas: {},
        orgId: 1,
        spuOrganizationList: [
          {
            orgId: 1
          }
        ],
        orgName: '',
        price: 0,
        productDescribe: '',
        productDescribeLanguageList: [],
        productName: '',
        productNameLanguageList: [],
        skuList: [],
        source: '2',
        spuAttributeList: [],
        spuImageList: [],
        taxIds: '',
        payment: {}
      },
      pageTitle: '',
      pageLoading: false,
      isSave: false,
      prodType: '',
      operationType: 'add',
      isShow: true
    }
  },
  created () {
    let routeParams = {}
    if (Object.keys(this.$route.params).length > 0) {
      setRouterParams(this.$route)
      routeParams = this.$route.params
    } else {
      routeParams = getRouterParams(this.$route)
    }
    const id = routeParams.id
    const name = this.$route.name
    const type = routeParams.type
    if (id && name === 'editProduct') {
      this.pageLoading = true
      // this.editAction(id)
    } else {
      this.showAddProduct()
    }
    if (name === 'addProduct') {
      this.pageTitle = '新增商品'
    } else {
      this.pageTitle = '修改商品'
    }
    if (type) {
      this.operationType = type
      if (type === 'preview') {
        this.parentModel.isPreview = true
        this.pageTitle = '查看商品'
      }
    }
    if (id) {
      this.parentModel.id = id
    }
  },
  beforeRouteLeave (to, from, next) {
    // 如果是第一步，只判断第一步
    const stepOneChanged = this.nowStep === 0 && this.$refs.stepOne.edited
    const stepTwoChanged = this.nowStep === 1 && this.$refs.stepTwo.isEdited
    if (stepOneChanged || stepTwoChanged) {
      this.isAlert = true
    }
    // 如果是第二部，只判断第二步
    if (this.isSave) {
      next()
    } else {
      if (this.isAlert && this.operationType !== 'preview') {
        this.$confirm('确定离开此页面？如果离开，更改将丢失', '', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          next()
        }).catch(() => {
          next(false)
          // this.$setMenuActived(this.$route)
        })
      } else {
        next()
      }
    }
  },
  mounted () {
    this.getNowOrgLangList()
  },
  methods: {
    alertFlag (data) {
      this.isAlert = data
    },
    startLoading () {
      this.pageLoading = true
    },
    editProduct (spuId) {
      const self = this
      if (spuId) {
        this.pageLoading = true
        const p1 = getSpuById(spuId)
        const p2 = getSkuById(spuId)
        this.pageLoading = true
        Promise.all([p1, p2]).then(result => {
          this.pageLoading = false
          // 获取到spu数据结果 [p1, p2]
          if (Number(result[0].code) === 1 && Number(result[1].code) === 1) {
            const proDatas = { ...Object.assign(result[1].obj, result[0].obj) }
            this.showStepOne = true
            this.$nextTick(_ => {
              self.showAddProduct(proDatas, 'back')
            })
          }
        }).catch(() => {
          this.pageLoading = false
        })
      }
    },
    // 总数据
    setModel (data) {
      this.parentModel = data
    },
    // 获取 langData
    getNowOrgLangList (initDatas) {
      // getOrgIdLanguage({ orgId: this.parentModel.orgId }).then(res => {
      //   if (res) {
      //     if (Number(res.code) === 1) {
      //       const langListDatas = res.obj
      //       localStorage.setItem(
      //         'productLangDatas',
      //         JSON.stringify(langListDatas)
      //       )
      //     } else {
      //       this.$confirm(this.$t(res.code), {
      //         confirmButtonText: '确定',
      //         showCancelButton: false
      //       })
      //     }
      //   }
      // })
    },
    // 显示添加商品弹窗
    showAddProduct (productDatas, initType) {
      this.nowStep = 0
      if (initType === 'back') {
        this.productDatas = null
        this.isEdit = true
        this.parentModel = {
          cancelable: '1',
          returnable: '1',
          catalogId: '',
          categoryDatas: {},
          orgId: 1,
          spuOrganizationList: [
            {
              orgId: 1
            }
          ],
          orgName: '',
          price: 0,
          productDescribe: '',
          productDescribeLanguageList: [],
          productName: '',
          productNameLanguageList: [],
          skuList: [],
          source: '1',
          spuAttributeList: [],
          spuImageList: [],
          taxIds: ''
        }
      }
      if (productDatas) {
        this.isEdit = true
        this.parentModel.isEdit = true
        this.productDatas = productDatas
        // 设置第一步数据
        this.parentModel.catalogId = productDatas.catalogId
        this.parentModel.id = productDatas.id
        this.parentModel.spuCode = productDatas.spuCode
        this.parentModel.spuOrganizationList = productDatas.spuOrganizationList
        // payment
        this.parentModel.payment = {
          paymentPeriod: productDatas.paymentPeriod,
          isRenewal: productDatas.isRenewal,
          isRelatedBundle: productDatas.isRelatedBundle,
          paymentType: productDatas.paymentType,
          bonusPeriod: productDatas.bonusPeriod
        }

        const initDatas = {
          categoryDatas: {}
        }
        initDatas.catalogId = productDatas.catalogId
        initDatas.cancelable = productDatas.cancelable
        initDatas.returnable = productDatas.returnable
        // payment
        // initDatas.paymentType = productDatas.paymentType
        // initDatas.paymentPeriod = productDatas.paymentPeriod
        // initDatas.isRenewal = productDatas.isRenewal
        // initDatas.isRelatedBundle = productDatas.isRelatedBundle
        // category list
        initDatas.catelogDatas = {
          codeList: [
            productDatas.firstId,
            productDatas.secondId,
            productDatas.thirdId
          ],
          nameList: [
            productDatas.firstName,
            productDatas.secondName,
            productDatas.thirdName
          ]
        }
        initDatas.productDescribeLanguageList = productDatas.productDescribeLanguageList
        initDatas.productNameLanguageList = productDatas.productNameLanguageList
        initDatas.spuImageList = productDatas.spuImageList
        initDatas.spuAttributeList = productDatas.spuAttributeList
        initDatas.source = productDatas.source
        initDatas.categoryList = productDatas.categoryList
        initDatas.spuOrganizationList = productDatas.spuOrganizationList
        initDatas.responseOrganizationTaxVo = productDatas.responseOrganizationTaxVo
        initDatas.responseSpuDeliveryList = productDatas.responseSpuDeliveryList

        initDatas.responseSkuList = productDatas.responseSkuList
        initDatas.spuSkuAttributeList = productDatas.spuSkuAttributeList
        this.pageLoading = false
        this.$nextTick(_ => {
          // this.$watch('productDatas', function () { this.Isupdate++ }, {deep: true})// 监听是否发生改变
          this.$refs.stepOne.initDatas(initDatas)
        })
      } else {
        this.productDatas = null
        this.$nextTick(_ => {
          this.pageLoading = false
          this.$refs.stepOne.initDatas()
        })
      }
    },
    // 上一步按钮是否展示
    showPre (data) {
      this.parentModel = data
      if (this.nowStep === 1 || this.nowStep === 2 || this.nowStep === 3) {
        return true
      }
      return false
    },
    // 下一步按钮是否展示
    showNext (data) {
      if (this.nowStep === 0 || this.nowStep === 1 || this.nowStep === 2) {
        return true
      }
      return false
    },
    // 提交按钮是否展示
    showSubmit () {
      if (this.nowStep === 2) {
        return true
      }
      return false
    },
    // 下一步数据初始化
    async next (initId, model) {
      getSpuById(initId).then(res => {
        if (res.obj) {
          const datas = res.obj
          model.id = datas.id
          const categoryList = []
          datas.categoryList.forEach(item => {
            const list = {
              categoryId: item.thirdId,
              channelCode: item.channelCode,
              channelName: item.channelName,
              id: item.id
            }
            categoryList.push(list)
          })
          model.categoryList = categoryList
          model.spuAttributeList = datas.spuAttributeList
          model.skuList = datas.responseSkuList
          this.submitDatas = model
        }
      })
      if (this.operationType === 'add') {
        this.operationType = 'edit'
        this.parentModel.id = initId
      }
      let initDatas = {}
      try {
        this.pageLoading = true
        const p2 = await getSkuById(initId)
        this.pageLoading = false
        if (Number(p2.code) === 1) {
          initDatas = p2.obj
        }
      } catch (e) {
        this.pageLoading = false
      }
      // 不同步骤设置不同传入数据
      if (this.nowStep === 0) {
        if (initDatas && initDatas.responseAutoOnOffSetVo) {
          const shelvesData = {}
          shelvesData.id = initDatas.responseAutoOnOffSetVo.id
          shelvesData.AvailableTime = [
            initDatas.responseAutoOnOffSetVo.buyCycleBeginDate,
            initDatas.responseAutoOnOffSetVo.buyCycleEndDate
          ]
          shelvesData.dateAvailableAble = Boolean(
            Number(initDatas.responseAutoOnOffSetVo.buyCycleFlag)
          )
          shelvesData.onShelfDateAble = Boolean(
            Number(initDatas.responseAutoOnOffSetVo.autoOnOffFlag)
          )
          const onShelfDate = initDatas.responseAutoOnOffSetVo.autoOnDate
          const offShelfDate = initDatas.responseAutoOnOffSetVo.autoOffDate
          shelvesData.onShelfTime = [onShelfDate, offShelfDate]
          shelvesData.allowBuy = Boolean(
            Number(initDatas.responseAutoOnOffSetVo.selloutAutoOffFlag)
          )
          initDatas.shelvesData = shelvesData
        }
        initDatas.paymentType = this.parentModel.paymentType
        this.$refs.stepTwo.initDatas(initDatas)
        // this.$nextTick(_ => {
        //   document.getElementsByClassName('el-drawer__body')[0].scrollTop = 0
        // })
      }
      if (this.nowStep++ > 2) this.nowStep = 0
    },
    // 取消操作，关闭弹窗
    closeDialog () {
      this.$router.push({ name: 'productMgmt' })
    },
    // 上一步
    prev (spuId) {
      this.pageLoading = true
      this.showStepOne = false
      this.editProduct(spuId)
      this.nowStep--
      if (this.nowStep < 0) this.nowStep = 0
    },
    // 获取商品信息
    getProductInfos (callback) {
      const p1 = getSpuById(this.parentModel.id)
      const p2 = getSkuById(this.parentModel.id)
      Promise.all([p1, p2]).then(result => {
        // 获取到spu数据结果 [p1, p2]
        if (Number(result[0].code) === 1 && Number(result[1].code) === 1) {
          const proDatas = { ...Object.assign(result[1].obj, result[0].obj) }
          callback(proDatas)
        }
      })
    },
    // 提交数据
    submit (model, type, operationType) {
      const submitDatas = model
      // console.log(submitDatas)
      this.pageLoading = true
      if (operationType === 'preview') {
        this.pageLoading = false
        Object.assign(this.parentModel, model)
        this.$nextTick(_ => {
          this.next(model.id, model)
        })
        return false
      }
      this.isShow = false
      productSave(submitDatas).then(res => {
        this.pageLoading = false
        if (res) {
          if (Number(res.code) === 1) {
            this.pageLoading = false
            if (type === 'next') {
              Object.assign(this.parentModel, model)
              // 点击确定时，首先后台获取数据，然后进行数据的初始化
              this.$nextTick(_ => {
                this.next(res.obj, model)
              })
            } else if (type === 'submit' || type === 'save') {
              // 添加成功
              this.parentModel = {}
              this.nowStep = 0
              this.pageLoading = false
              this.isSave = true
              this.$alert('保存成功', {
                confirmButtonText: '确定',
                callback: action => {
                  this.$router.push({ name: 'productMgmt' })
                }
              })
            } else {
              this.pageLoading = false
              this.$alert('保存成功')
            }
          } else {
            this.$confirm(this.$t(res.code), {
              confirmButtonText: '确定',
              showCancelButton: false
            })
            this.pageLoading = false
          }
        }
        this.pageLoading = false
      }).catch(() => {
        this.pageLoading = false
      })
    },
    editAction (id) {
      this.pageLoading = true
      getSpuById(id).then(result => {
        // 获取到spu数据结果 [p1, p2]
        this.pageLoading = false
        if (Number(result.code) === 1) {
          const proDatas = result.obj
          this.showAddProduct(proDatas)
        } else {
          this.pageLoading = false
        }
      }).catch(() => {
        this.pageLoading = false
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.stepStyle {
  .is-process {
    .el-step__icon-inner {
      border: 1px solid #000;
    }
  }
}
.stepButtonSty {
  float: right;
  margin-right: 10px;
}
</style>
<style>
.el-step__icon{
  background: #f5f5f5!important;
}
</style>
